using System.Threading.Channels;
using NotifyCenter.MediatR.Etos;

namespace NotifyCenter.MediatR.Webhooks;

public interface INotificationWebhookQueue
{
    ValueTask EnqueueAsync(NotificationWebhookEto notification, CancellationToken cancellationToken = default);
    ValueTask<NotificationWebhookEto> DequeueAsync(CancellationToken cancellationToken);
}

public class NotificationWebhookQueue : INotificationWebhookQueue
{
    private readonly Channel<NotificationWebhookEto> channel;

    public NotificationWebhookQueue()
    {
        channel = Channel.CreateUnbounded<NotificationWebhookEto>(new UnboundedChannelOptions
        {
            SingleReader = true,
            SingleWriter = false
        });
    }

    public ValueTask EnqueueAsync(NotificationWebhookEto notification, CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(notification);
        return channel.Writer.WriteAsync(notification, cancellationToken);
    }

    public ValueTask<NotificationWebhookEto> DequeueAsync(CancellationToken cancellationToken)
    {
        return channel.Reader.ReadAsync(cancellationToken);
    }
}
